#coding=utf-8
from uliweb.core.SimpleFrame import expose, url_for
from uliweb.contrib.auth.views import login, register, logout

expose('/login')(login)
expose('/register')(register)
expose('/logout')(logout)

from uliweb.utils.common import wraps          
def require_login(f):
    @wraps(f)
    def _f(*args):
        if not request.user:
            return redirect(url_for(login) + '?next=%s' % request.path)
        return f(*args)
    return _f

@require_login
@expose('/admin')
def admin():
    from uliweb.contrib.auth.forms import ChangePasswordForm
    from forms import ChangeInfoForm
    
    changepasswordform = ChangePasswordForm()
    changeinfoform = ChangeInfoForm()
    changeinfoform.email.data = request.user.email
    changeinfoform.image.data = request.user.image
    if request.method == 'GET':
        return {'changepasswordform':changepasswordform, 'changeinfoform':changeinfoform}
    if request.method == 'POST':
        if request.POST.get('action') == 'changepassword':
            flag = changepasswordform.validate(request.POST, request=request)
            if flag:
                request.user.set_password(changepasswordform.password.data)
                return redirect(request.path)
            else:
                message = "There was something wrong! Please fix them."
                return {'changepasswordform':changepasswordform, 
                    'changeinfoform':changeinfoform, 'message':message}
        if request.POST.get('action') == 'changeinfo':
            flag = changeinfoform.validate(request.POST, request.FILES)
            if flag:
                #saving image
                if changeinfoform.image.data:
                    #using save_image_field
                     from uliweb.contrib.upload import save_image_field
                     save_image_field(changeinfoform.image, replace=True, 
                        subfolder='portrait', resize_to=(50, 50), application=application)
#using save_file_field
#                    from uliweb.contrib.upload import save_file_field
#                    save_file_field(changeinfoform.image, replace=True, subfolder='portrait')
#old usage
#                    changeinfoform.image.data.filename = save_file(changeinfoform.image.data.filename, 
#                        changeinfoform.image.data.file, replace=True, subfolder='portrait')
#                    profile.image = changeinfoform.image.data.filename
                request.user.image = changeinfoform.image.data.filename
                request.user.email = changeinfoform.email.data
                request.user.save()
                return redirect(request.path)
            else:
                message = "There was something wrong! Please fix them."
                return {'changepasswordform':changepasswordform, 
                    'changeinfoform':changeinfoform, 'message':message}
            
    
